package com.street.service.impl;

import com.street.context.BaseContext;
import com.street.dto.CartDTO;
import com.street.entity.Cart;
import com.street.entity.Dish;
import com.street.mapper.CartMapper;
import com.street.mapper.DishMapper;
import com.street.service.CartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    DishMapper dishMapper;
    @Override
    public List<Cart> list(Long shopId) {
        Long userId = BaseContext.getCurrentId();
        Cart cart=new Cart();
        cart.setUserId(userId);
        cart.setShopId(shopId);
        List<Cart>cartList=cartMapper.list(cart);
        return cartList;
    }

    @Override
    public void add(CartDTO cartDTO) {
        //判断是否已经存在该商品，如果有就将数量加1，没有的话就新增
        Long userId = BaseContext.getCurrentId();
        Cart cartQueue=new Cart();
        BeanUtils.copyProperties(cartDTO,cartQueue);
        cartQueue.setUserId(userId);
        List<Cart> list = cartMapper.list(cartQueue);
        if(list!=null&&list.size()>0){
            //数量加一
            Cart cart=list.get(0);
            cart.setNumber(cart.getNumber()+1);
            cartMapper.update(cart);
        }
        else{
            Long dishId= cartDTO.getDishId();
            Dish dish = dishMapper.selectById(dishId);
            cartQueue.setAmount(dish.getPrice());
            cartQueue.setImage(dish.getImage());
            cartQueue.setName(dish.getName());
            cartQueue.setNumber(1);
            cartQueue.setCreateTime(LocalDateTime.now());
            cartMapper.insert(cartQueue);
        }
    }

    @Override
    public void delete(CartDTO cartDTO) {
        //检查num是大于一还是等于一，大于一就减一，等于一就删除
        Cart cartQueue=new Cart();
        BeanUtils.copyProperties(cartDTO,cartQueue);
        Long userId = BaseContext.getCurrentId();
        cartQueue.setUserId(userId);
        List<Cart> list = cartMapper.list(cartQueue);
        //防止空指针
        if(list==null||list.size()<1){
            return;
        }
        //获取到该项，并且给他的数目减一
        Cart cart = list.get(0);
        cart.setNumber(cart.getNumber()-1);

        if(cart.getNumber()==0){
            //如果数目等于0就删除
            cartMapper.deleteById(cart.getId());
        }
        else{
            //大于0就减一
            cartMapper.update(cart);
        }
    }

    @Override
    public void clear(Long shopId) {
        Long userId=BaseContext.getCurrentId();
        cartMapper.clear(userId,shopId);
    }
}
